package serv_cmd

import (
	"context"
	"encoding/json"

	"atomgit.com/openlinksaas/proto-gen-go.git/swarm_proxy_api"
	"atomgit.com/openlinksaas/swarm_api_proxy/config"
	"atomgit.com/openlinksaas/swarm_api_proxy/utils"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/api/types/swarm"
)

func (apiImpl *SwarmProxyApiImpl) getUserPerm(ctx context.Context, projectId, userId string) *swarm_proxy_api.UserPerm {
	c, err := utils.GetDockerClient(apiImpl.cfg.ServerUrl, apiImpl.cfg.CertPath)
	if err != nil {
		return &swarm_proxy_api.UserPerm{}
	}
	defer c.Close()

	filter := filters.NewArgs()
	filter.Add("name", config.PERM_CONFIG_KEY+projectId)
	cfgItemList, err := c.ConfigList(ctx, types.ConfigListOptions{
		Filters: filter,
	})
	if err != nil {
		return &swarm_proxy_api.UserPerm{}
	}
	permList := []*swarm_proxy_api.UserPerm{}

	for _, cfgItem := range cfgItemList {
		if cfgItem.Spec.Name == (config.PERM_CONFIG_KEY + projectId) {
			err = json.Unmarshal(cfgItem.Spec.Data, &permList)
			if err != nil {
				return &swarm_proxy_api.UserPerm{}
			}
		}
	}
	for _, userPerm := range permList {
		if userPerm.UserId == userId {
			return userPerm
		}
	}
	return &swarm_proxy_api.UserPerm{}
}

func (apiImpl *SwarmProxyApiImpl) GetPerm(ctx context.Context, req *swarm_proxy_api.GetPermRequest) (*swarm_proxy_api.GetPermResponse, error) {
	emptyList := []*swarm_proxy_api.UserPerm{}

	//检查权限
	tokenInfo, err := apiImpl.getTokenInfo(apiImpl.cfg.LinkSaasAddr, req.Token)
	if err != nil {
		return &swarm_proxy_api.GetPermResponse{
			Code:         swarm_proxy_api.GetPermResponse_CODE_WRONG_TOKEN,
			ErrMsg:       "错误的访问令牌",
			UserPermList: emptyList,
		}, nil
	}
	c, err := utils.GetDockerClient(apiImpl.cfg.ServerUrl, apiImpl.cfg.CertPath)
	if err != nil {
		return nil, err
	}
	defer c.Close()

	exist, err := apiImpl.existProject(ctx, c, tokenInfo.ProjectId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &swarm_proxy_api.GetPermResponse{
			Code:         swarm_proxy_api.GetPermResponse_CODE_NO_PERMISSION,
			ErrMsg:       "没有权限",
			UserPermList: emptyList,
		}, nil
	}

	filter := filters.NewArgs()
	filter.Add("name", config.PERM_CONFIG_KEY+tokenInfo.ProjectId)
	cfgItemList, err := c.ConfigList(ctx, types.ConfigListOptions{
		Filters: filter,
	})
	if err != nil {
		return nil, err
	}
	permList := []*swarm_proxy_api.UserPerm{}

	for _, cfgItem := range cfgItemList {
		if cfgItem.Spec.Name == (config.PERM_CONFIG_KEY + tokenInfo.ProjectId) {
			err = json.Unmarshal(cfgItem.Spec.Data, &permList)
			if err != nil {
				return nil, err
			}
		}
	}
	return &swarm_proxy_api.GetPermResponse{
		Code:         swarm_proxy_api.GetPermResponse_CODE_OK,
		UserPermList: permList,
	}, nil
}

func (apiImpl *SwarmProxyApiImpl) SetPerm(ctx context.Context, req *swarm_proxy_api.SetPermRequest) (*swarm_proxy_api.SetPermResponse, error) {
	//检查权限
	tokenInfo, err := apiImpl.getTokenInfo(apiImpl.cfg.LinkSaasAddr, req.Token)
	if err != nil {
		return &swarm_proxy_api.SetPermResponse{
			Code:   swarm_proxy_api.SetPermResponse_CODE_WRONG_TOKEN,
			ErrMsg: "错误的访问令牌",
		}, nil
	}
	if !tokenInfo.Admin {
		return &swarm_proxy_api.SetPermResponse{
			Code:   swarm_proxy_api.SetPermResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	c, err := utils.GetDockerClient(apiImpl.cfg.ServerUrl, apiImpl.cfg.CertPath)
	if err != nil {
		return nil, err
	}
	defer c.Close()

	exist, err := apiImpl.existProject(ctx, c, tokenInfo.ProjectId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &swarm_proxy_api.SetPermResponse{
			Code:   swarm_proxy_api.SetPermResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	filter := filters.NewArgs()
	filter.Add("name", config.PERM_CONFIG_KEY+tokenInfo.ProjectId)
	tmpCfgItemList, err := c.ConfigList(ctx, types.ConfigListOptions{
		Filters: filter,
	})
	if err != nil {
		return nil, err
	}
	cfgItemList := []swarm.Config{}
	for _, cfgItem := range tmpCfgItemList {
		if cfgItem.Spec.Name == (config.PERM_CONFIG_KEY + tokenInfo.ProjectId) {
			cfgItemList = append(cfgItemList, cfgItem)
		}
	}

	if len(cfgItemList) > 0 {
		err = c.ConfigRemove(ctx, cfgItemList[0].ID)
		if err != nil {
			return nil, err
		}
	}
	jsonData, err := json.Marshal(req.UserPermList)
	if err != nil {
		return nil, err
	}
	_, err = c.ConfigCreate(ctx, swarm.ConfigSpec{
		Annotations: swarm.Annotations{
			Name: config.PERM_CONFIG_KEY + tokenInfo.ProjectId,
		},
		Data: jsonData,
	})
	if err != nil {
		return nil, err
	}
	return &swarm_proxy_api.SetPermResponse{
		Code: swarm_proxy_api.SetPermResponse_CODE_OK,
	}, nil
}
